package pers.bc.utils.net;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.security.cert.X509Certificate;

public class IEProxyApiCaller
{
    // 代理服务器设置
    private static final String PROXY_HOST = "your-proxy-host"; // 替换为实际代理服务器IP
    private static final int PROXY_PORT = 8080; // 替换为实际代理端口
    private static final String PROXY_USERNAME = "your-username"; // 如果需要认证
    private static final String PROXY_PASSWORD = "your-password"; // 如果需要认证
    
    // 目标API地址
    private static final String API_URL = "https://api.example.com/endpoint"; // 替换为实际API地址
    
    public static void main(String[] args)
    {
        try
        {
            // 设置代理认证（如果需要）
            if (!PROXY_USERNAME.isEmpty() && !PROXY_PASSWORD.isEmpty())
            {
                Authenticator.setDefault(new Authenticator()
                {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication()
                    {
                        return new PasswordAuthentication(PROXY_USERNAME, PROXY_PASSWORD.toCharArray());
                    }
                });
            }
            
            // 创建代理对象
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT));
            
            // 创建URL对象
            URL url = new URL(API_URL);
            
            // 打开连接
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(proxy);
            
            // 设置IE浏览器典型的请求头
            connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0");
            connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.setRequestProperty("Connection", "keep-alive");
            
            // 设置超时时间
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            
            // 信任所有SSL证书（仅用于测试环境，生产环境应使用正式证书）
            trustAllCertificates();
            
            // 发送请求
            connection.setRequestMethod("GET");
            
            // 获取响应代码
            int responseCode = connection.getResponseCode();
            System.out.println("响应代码: " + responseCode);
            
            // 读取响应内容
            if (responseCode == HttpsURLConnection.HTTP_OK)
            {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                
                while ((inputLine = in.readLine()) != null)
                {
                    response.append(inputLine);
                }
                in.close();
                
                System.out.println("API响应内容: " + response.toString());
            }
            else
            {
                System.out.println("API请求失败，错误代码: " + responseCode);
            }
            
            // 断开连接
            connection.disconnect();
            
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    // 信任所有SSL证书（仅用于测试环境）
    private static void trustAllCertificates()
    {
        try
        {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager()
            {
                public X509Certificate[] getAcceptedIssuers()
                {
                    return null;
                }
                
                public void checkClientTrusted(X509Certificate[] certs, String authType)
                {
                }
                
                public void checkServerTrusted(X509Certificate[] certs, String authType)
                {
                }
            }};
            
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            
            // 忽略主机名验证（仅用于测试）
            // HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
            
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
